package csgbd.Hotel.GUI;

import csgbd.Hotel.Common.DB.ConnectionFactory;
import csgbd.Hotel.Common.Entity.Room;
import csgbd.Hotel.Common.Entity.RoomType;
import csgbd.Hotel.Common.Facade.Default.HotelFacade;
import csgbd.Hotel.Common.Facade.IHotelFacade;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author italopessoa
 */
public class jfrmRoom extends javax.swing.JFrame {

    private ArrayList<Room> rooms;
    private ArrayList<RoomType> roomsTypes;
    private IHotelFacade facade;
    
    /**
     * Creates new form jfrmRoom
     */
    public jfrmRoom() {
        initComponents();
        ConnectionFactory.OpenConnection();
        this.facade = new HotelFacade();
        this.showRoomTypes();
        this.enableFiltersPanel(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jbtnClear = new javax.swing.JButton();
        jbtnNewRoomType = new javax.swing.JButton();
        jtxtId = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbGuests = new javax.swing.JTable();
        jbtnRemoveRoomType = new javax.swing.JButton();
        jbtnEditRoomType = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jtxtPrice = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jpnlFilters = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jcbxType = new javax.swing.JCheckBox();
        jcbxPrice = new javax.swing.JCheckBox();
        jcbxGreaterThan = new javax.swing.JCheckBox();
        jbtnOk = new javax.swing.JButton();
        jbtnSearchRoom = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jbtnClear.setText("Clear");
        jbtnClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnClearActionPerformed(evt);
            }
        });

        jbtnNewRoomType.setText("Save");
        jbtnNewRoomType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNewRoomTypeActionPerformed(evt);
            }
        });

        jtxtId.setEditable(false);
        jtxtId.setEnabled(false);

        jtbGuests.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "ID", "Price", "Type"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtbGuests.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtbGuestsMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtbGuests);

        jbtnRemoveRoomType.setText("Remove");
        jbtnRemoveRoomType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnRemoveRoomTypeActionPerformed(evt);
            }
        });

        jbtnEditRoomType.setText("Update");
        jbtnEditRoomType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnEditRoomTypeActionPerformed(evt);
            }
        });

        jLabel1.setText("ID:");

        jLabel3.setText("Type:");

        jLabel4.setText("Price:");

        jLabel2.setText("Filters:");

        jcbxType.setText("Type");
        jcbxType.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcbxTypeItemStateChanged(evt);
            }
        });

        jcbxPrice.setText("Price");
        jcbxPrice.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcbxPriceItemStateChanged(evt);
            }
        });

        jcbxGreaterThan.setText("Greater than");

        jbtnOk.setText("Ok");
        jbtnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnOkActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpnlFiltersLayout = new javax.swing.GroupLayout(jpnlFilters);
        jpnlFilters.setLayout(jpnlFiltersLayout);
        jpnlFiltersLayout.setHorizontalGroup(
            jpnlFiltersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnlFiltersLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(jcbxType)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcbxPrice)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jcbxGreaterThan)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnOk)
                .addContainerGap(41, Short.MAX_VALUE))
        );
        jpnlFiltersLayout.setVerticalGroup(
            jpnlFiltersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnlFiltersLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnlFiltersLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jcbxType)
                    .addComponent(jcbxPrice)
                    .addComponent(jcbxGreaterThan)
                    .addComponent(jbtnOk))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jbtnSearchRoom.setText("Search");
        jbtnSearchRoom.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnSearchRoomActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(39, 39, 39)
                        .addComponent(jtxtId, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addComponent(jtxtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(12, 12, 12)
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jpnlFilters, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jbtnNewRoomType)
                        .addGap(6, 6, 6)
                        .addComponent(jbtnEditRoomType)
                        .addGap(6, 6, 6)
                        .addComponent(jbtnRemoveRoomType)
                        .addGap(6, 6, 6)
                        .addComponent(jbtnClear)
                        .addGap(6, 6, 6)
                        .addComponent(jbtnSearchRoom))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 388, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabel1))
                    .addComponent(jtxtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jtxtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3))))
                .addGap(6, 6, 6)
                .addComponent(jpnlFilters, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtnNewRoomType)
                    .addComponent(jbtnEditRoomType)
                    .addComponent(jbtnRemoveRoomType)
                    .addComponent(jbtnClear)
                    .addComponent(jbtnSearchRoom))
                .addGap(6, 6, 6)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnClearActionPerformed
        this.clearRoomValues();
    }//GEN-LAST:event_jbtnClearActionPerformed

    private void jbtnNewRoomTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNewRoomTypeActionPerformed
        Room room = new Room(Double.parseDouble(this.jtxtPrice.getText()), this.getSelectedRoomType());
        this.newRoom(room);
        this.showRooms();
    }//GEN-LAST:event_jbtnNewRoomTypeActionPerformed

    private void jtbGuestsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtbGuestsMouseClicked
        int linha = this.jtbGuests.getSelectedRow();
        if(linha >-1){
            this.jtxtId.setText(String.valueOf(this.jtbGuests.getValueAt(linha,0)));
            this.jtxtPrice.setText(String.valueOf(this.jtbGuests.getValueAt(linha,1)));
        }
    }//GEN-LAST:event_jtbGuestsMouseClicked

    private void jbtnRemoveRoomTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnRemoveRoomTypeActionPerformed
        Room room = new Room(Integer.parseInt(this.jtxtId.getText()));
        this.removeRoom(room);
    }//GEN-LAST:event_jbtnRemoveRoomTypeActionPerformed

    private void jbtnEditRoomTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnEditRoomTypeActionPerformed
        Room room = new Room(Integer.parseInt(this.jtxtId.getText()));
        //room.setName(this.jtxtName.getText());

        this.updateRoomType(room);
    }//GEN-LAST:event_jbtnEditRoomTypeActionPerformed

    private void jbtnSearchRoomActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnSearchRoomActionPerformed
        this.enableFiltersPanel(true);
    }//GEN-LAST:event_jbtnSearchRoomActionPerformed

    private void jcbxPriceItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbxPriceItemStateChanged
        if(this.jcbxPrice.isSelected()){
            this.jcbxGreaterThan.setEnabled(true);
        }
        else {
            this.jcbxGreaterThan.setEnabled(false); 
        }
    }//GEN-LAST:event_jcbxPriceItemStateChanged

    private void jcbxTypeItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbxTypeItemStateChanged
    }//GEN-LAST:event_jcbxTypeItemStateChanged

    private void jbtnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnOkActionPerformed
        
        RoomType roomType = null;
        Double price = null;
        if (this.jcbxType.isSelected()){
            roomType = (RoomType)this.jComboBox1.getSelectedItem();
        }
        
        if (this.jcbxPrice.isSelected()){
            price = Double.parseDouble(jtxtPrice.getText());
        }
        try {        
            this.rooms = this.facade.SelectRoomsByTypeOrPrice(roomType, price, this.jcbxGreaterThan.isSelected());
        } catch (SQLException ex) {
            Logger.getLogger(jfrmRoom.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(jfrmRoom.class.getName()).log(Level.SEVERE, null, ex);
        }finally{
            this.showRooms();
            this.enableFiltersPanel(false);
        }
        
    }//GEN-LAST:event_jbtnOkActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(jfrmRoom.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(jfrmRoom.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(jfrmRoom.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(jfrmRoom.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new jfrmRoom().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtnClear;
    private javax.swing.JButton jbtnEditRoomType;
    private javax.swing.JButton jbtnNewRoomType;
    private javax.swing.JButton jbtnOk;
    private javax.swing.JButton jbtnRemoveRoomType;
    private javax.swing.JButton jbtnSearchRoom;
    private javax.swing.JCheckBox jcbxGreaterThan;
    private javax.swing.JCheckBox jcbxPrice;
    private javax.swing.JCheckBox jcbxType;
    private javax.swing.JPanel jpnlFilters;
    private javax.swing.JTable jtbGuests;
    private javax.swing.JTextField jtxtId;
    private javax.swing.JTextField jtxtPrice;
    // End of variables declaration//GEN-END:variables

    private void getRooms(){
        try {
            this.rooms = this.facade.SelectAllRooms();
        } catch (SQLException ex) {
            Logger.getLogger(jfrmRoom.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(jfrmRoom.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void showRooms() {
        //this.getRooms();
        DefaultTableModel model = (DefaultTableModel) this.jtbGuests.getModel();
        model.setNumRows(0);

        for (Room room : this.rooms) {
            model.addRow(new Object[]{room.getId(), room.getPrice(),room.getType()});
        }
    }
    
    private void newRoom(Room room){
        try {
            this.facade.NewRoom(room);
            JOptionPane.showMessageDialog(null, "Guest saved sucefull!");
        } catch (SQLException ex) {
            Logger.getLogger(jfrmRoom.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(jfrmRoom.class.getName()).log(Level.SEVERE, null, ex);
        }
            
    }
    
    private void removeRoom(Room room){
        try {
            this.facade.RemoveRoom(room);
        } catch (Exception ex) {
            Logger.getLogger(jfrmRoom.class.getName()).log(Level.SEVERE, null, ex);
        }
        JOptionPane.showMessageDialog(null, "Guest removed sucefull!");
        this.showRooms();
        this.clearRoomValues();
    }
    
    private void updateRoomType(Room room){
        try {
            this.facade.UpdateRoom(room);
            JOptionPane.showMessageDialog(null, "Guest updated sucefull!");
        } catch (SQLException ex) {
            Logger.getLogger(jfrmRoom.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(jfrmRoom.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.showRooms();
        this.clearRoomValues();
    }
    
    private void clearRoomValues(){
        this.jtxtId.setText("");
        this.jtxtPrice.setText("");
    }
    
    private void showRoomTypes(){
        try {
            this.roomsTypes = this.facade.SelectAllRoomTypes();
        } catch (SQLException ex) {
            Logger.getLogger(jfrmRoom.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(jfrmRoom.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        for(RoomType roomType  : this.roomsTypes) {
            this.jComboBox1.addItem(roomType);
        }
    }
    
    private RoomType getSelectedRoomType(){
        return (RoomType)this.jComboBox1.getSelectedItem();
    }
    
    private void enableFiltersPanel(boolean enabled){
        this.jpnlFilters.setEnabled(enabled);
        this.jcbxType.setEnabled(enabled);
        this.jcbxPrice.setEnabled(enabled);
        if(!enabled){
            this.jcbxGreaterThan.setEnabled(enabled);
        }
        this.jbtnOk.setEnabled(enabled);
    }
}